package com.psct.imageCache;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import com.psct.R;
import com.psct.ThreadPool;
import com.psct.imageCache.ImageCache.ImageCacheParams;

public class ImageCacheManager {
	private static final String TAG = "iamgeCahe";

	private static ImageCacheManager manager;
	private final String IMAGE_CACHE_DIR = "psct";
	private int mImageThumbSize;
	private int mImageThumbSpacing;
	private Context context;
	private  ImageCache mImageCache;

	/**
	 * 私有构造方法
	 * @param context
	 */
	private ImageCacheManager(Context context) {
		this.context=context;
		if (mImageCache == null)
			init(context);
	}

	/**
	 * 单例方法
	 * @param context
	 * @return
	 */
	public static ImageCacheManager getInstance(Context context) {
		if (manager == null) {
			manager = new ImageCacheManager(context);
		}
		return manager;
	}

	/**
	 * 初始化缓存
	 * @param context
	 */
	private void init(Context context) {
		mImageThumbSize = context.getResources()
				.getDimensionPixelSize(R.dimen.image_thumbnail_size);
		mImageThumbSpacing = context.getResources().getDimensionPixelSize(
				R.dimen.image_thumbnail_spacing);
		ImageCacheParams cacheParams = new ImageCacheParams(context, IMAGE_CACHE_DIR);
		// 设置内存的四分之一缓存图片
		cacheParams.setMemCacheSizePercent(context, 0.2f);
		mImageCache = new ImageCache(cacheParams);
	}
	
	/**
	 * 获得sd卡缓存的目录
	 * @return
	 */
	public File getFile(String url) {
		String dir = ImageCache.getExternalCacheDir(context).getAbsolutePath();
		File file = new File(dir+ImageCache.hashKeyForDisk(url));
		return file;
	}
	
	/**
	 * 从缓存中获取图片
	 * @param url 图片的url
	 * @param callBack 如果缓存中不存在则去服务器下载，下载完成后调用此接口的方法
	 * @return bitmap 不存在则返回null
	 */
	public Bitmap getBitmap(final String url , final ImageLoadCallBack callBack) {
		//查询内存
		Bitmap bitmap = mImageCache.getBitmapFromMemCache(url);
		System.out.println("内存查询结果："+bitmap);
		if(bitmap!=null&&!bitmap.isRecycled()) {//如果内存中存在此bitmap，返回
			return bitmap;
		}
		//查询硬盘
		ThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Bitmap b = mImageCache.getBitmapFromDiskCache(url);
				System.out.println("硬盘查询结果："+b+"。文件名："+ImageCache.hashKeyForDisk(url));
				if(b!=null) {//如果内存中不存在，硬盘存在，添加到内存并返回
					mImageCache.addBitmapToMemoryCache(url, b);
				}else {//内存和硬盘都不存在此bitmap，则去服务器下载
					b=loadBitmapFromUrl(url);
					if(b==null) {
						if(callBack!=null) {
							callBack.onImageLoadErr();
						}
						return;
					}
					mImageCache.addBitmapToCache(url, b);
				}
				if(callBack!=null)
				callBack.onImageLoaded(b);
			}
		});
		return null;
	}
	
	/**
	 * 服务器下载图片
	 * @param url
	 * @return
	 */
	private Bitmap loadBitmapFromUrl(String url) {
		try {
			BufferedInputStream in =  new BufferedInputStream(new URL(url).openStream());
			return BitmapFactory.decodeStream(in);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 图片加载完后的回调接口
	 * @author zjingchuan
	 *
	 */
	public interface ImageLoadCallBack{
		void onImageLoaded(Bitmap bitmap);
		 void onImageLoadErr();
	}
}
